package com.hurt.competition.player.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hurt.competition.admin.dto.CompetitionReq;
import com.hurt.competition.admin.model.Competition;
import com.hurt.competition.admin.service.CompetitionService;
import com.hurt.competition.common.enums.PlayerStateEnum;
import com.hurt.competition.common.exception.CoreException;
import com.hurt.competition.common.vo.PageResult;
import com.hurt.competition.judge.model.CompetitionJudge;
import com.hurt.competition.judge.service.CompetitionJudgeService;
import com.hurt.competition.player.dto.CompetitionPlayerListRes;
import com.hurt.competition.player.dto.CompetitionPlayerReq;
import com.hurt.competition.player.dto.ScoreDataDto;
import com.hurt.competition.player.mapper.CompetitionPlayerMapper;
import com.hurt.competition.player.model.CompetitionJudgePlayer;
import com.hurt.competition.player.model.CompetitionPlayer;
import com.hurt.competition.player.model.SysUser;
import com.hurt.competition.player.service.CompetitionPlayerService;
import com.hurt.competition.player.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CompetitionPlayerServiceImpl extends ServiceImpl<CompetitionPlayerMapper, CompetitionPlayer> implements CompetitionPlayerService {

    @Autowired
    private CompetitionService competitionService;

    @Autowired
    private CompetitionJudgeService competitionJudgeService;

    @Autowired
    private SysUserService sysUserService;

    @Override
    public PageResult<Competition> page(CompetitionPlayerReq req) {
        LambdaQueryWrapper<CompetitionPlayer> queryWrapper = new LambdaQueryWrapper<>();
        // 模糊查询，like方法的第一个参数为条件，如果为true，则进行后续的操作
        queryWrapper
                .eq(req.getUserId()!=null, CompetitionPlayer::getUserId, req.getUserId())
                .eq(req.getCompetitionId()!=null, CompetitionPlayer::getCompetitionId, req.getCompetitionId())
                .eq(StringUtils.isNotBlank(req.getState()), CompetitionPlayer::getState, req.getState());
        List<CompetitionPlayer> list = list(queryWrapper);

        if(CollectionUtils.isEmpty(list)){
            return  new PageResult();
        }

        PageResult<Competition> competitionPageResult = competitionService.queryList(new CompetitionReq() {{
            setCompetitionIdList(list.stream().map(e->e.getCompetitionId()).collect(Collectors.toList()));
            setPageNumber(req.getPageNumber());
            setPageSize(req.getPageSize());
        }});
        return competitionPageResult;
    }

    @Override
    public PageResult<CompetitionPlayerListRes> queryList(CompetitionPlayerReq req) {
        PageResult pageResult = new PageResult();
        Page<Competition> page = PageHelper.startPage(req.getPageNumber(), req.getPageSize());

        LambdaQueryWrapper<CompetitionPlayer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(req.getCompetitionId()!=null,CompetitionPlayer::getCompetitionId,req.getCompetitionId());

        List<CompetitionPlayer> playerList = list(queryWrapper);
        if(CollectionUtils.isEmpty(playerList)){
            return pageResult;
        }

        // 查询用户
        List<CompetitionPlayerListRes> resList = handlerList(playerList);
        pageResult.setList(resList);
        pageResult.setTotal(page.getTotal());
        return pageResult;
    }

    @Override
    public ScoreDataDto queryData(Integer competitionId) {
        ScoreDataDto scoreDataDto = this.baseMapper.queryData(competitionId);
        return scoreDataDto;
    }

    @Override
    public CompetitionPlayer info(CompetitionPlayerReq req) {
        LambdaQueryWrapper<CompetitionPlayer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(CompetitionPlayer::getCompetitionId,req.getCompetitionId())
                .eq(CompetitionPlayer::getUserId,req.getUserId());
        CompetitionPlayer record = getOne(queryWrapper);
        return record;
    }

    private List<CompetitionPlayerListRes> handlerList(List<CompetitionPlayer> playerList) {
        if(CollectionUtils.isEmpty(playerList)){
            return Collections.EMPTY_LIST;
        }

        Set<Integer> userIdSet = playerList.stream().map(e -> e.getUserId()).collect(Collectors.toSet());
        List<SysUser> sysUsers = sysUserService.listByIds(userIdSet);

        if(CollectionUtils.isEmpty(sysUsers)){
            return Collections.EMPTY_LIST;
        }
        Map<Integer, SysUser> userMap = sysUsers.stream().collect(Collectors.toMap(e -> e.getId(), e -> e));

        List<CompetitionPlayerListRes> resList = new ArrayList<>(playerList.size());
        for (CompetitionPlayer competitionPlayer : playerList) {
            CompetitionPlayerListRes res = new CompetitionPlayerListRes();
            SysUser sysUser = userMap.get(competitionPlayer.getUserId());
            if(sysUser!=null){
                res.setRealName(sysUser.getRealName());
            }
            res.setCompetitionId(competitionPlayer.getCompetitionId());
            res.setUserId(competitionPlayer.getUserId());
            resList.add(res);
        }

        return resList;
    }

    @Override
    public void regisCompetition(CompetitionPlayer competitionPlayer) {
        LambdaQueryWrapper<CompetitionPlayer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(CompetitionPlayer::getCompetitionId,competitionPlayer.getCompetitionId())
                .eq(CompetitionPlayer::getUserId,competitionPlayer.getUserId());
        CompetitionPlayer record = getOne(queryWrapper);
        if(record != null){
            throw new CoreException("该选手已参加该比赛");
        }
        competitionPlayer.setState(PlayerStateEnum.ENTRY.getCode());
        save(competitionPlayer);
    }

    @Override
    public void audit(CompetitionPlayer competitionPlayer) {
        LambdaUpdateWrapper<CompetitionPlayer> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .eq(CompetitionPlayer::getCompetitionId,competitionPlayer.getCompetitionId())
                .eq(CompetitionPlayer::getUserId,competitionPlayer.getUserId());
        CompetitionPlayer record = getOne(updateWrapper);
        if(record == null){
            throw new CoreException("未查到该报名信息");
        }

        updateWrapper.set(CompetitionPlayer::getState,competitionPlayer.getState());
        update(updateWrapper);
    }

    @Override
    public void uploadProject(CompetitionPlayer competitionPlayer) {
        // 检测该比赛里，此选手是否生效
        checkEnablePlayer(competitionPlayer);

        LambdaUpdateWrapper<CompetitionPlayer> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .eq(CompetitionPlayer::getCompetitionId,competitionPlayer.getCompetitionId())
                .eq(CompetitionPlayer::getUserId,competitionPlayer.getUserId())
                .set(CompetitionPlayer::getFileName,competitionPlayer.getFileName());

        update(updateWrapper);
    }

    @Override
    public void scoring(CompetitionPlayer competitionPlayer) {
        // 校验该比赛里，此评委是否生效
        //competitionJudgeService.checkEnableJudge(new CompetitionJudge(){{
        //    setGId(competitionPlayer.getGId());
        //    setJId(competitionPlayer.getJId());
        //}});
        // 检测该比赛里，此选手是否生效
        checkEnablePlayer(competitionPlayer);

        checkEnablePlayer(competitionPlayer);

        LambdaUpdateWrapper<CompetitionPlayer> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper
                .eq(CompetitionPlayer::getCompetitionId,competitionPlayer.getCompetitionId())
                .eq(CompetitionPlayer::getUserId,competitionPlayer.getUserId())
                .set(CompetitionPlayer::getScore,competitionPlayer.getScore());
        update(updateWrapper);
    }

    @Override
    public void checkEnablePlayer(CompetitionPlayer competitionPlayer) {
        LambdaQueryWrapper<CompetitionPlayer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(CompetitionPlayer::getCompetitionId,competitionPlayer.getCompetitionId())
                .eq(CompetitionPlayer::getUserId,competitionPlayer.getUserId());

        CompetitionPlayer player = getOne(queryWrapper);
        if(player == null){
            throw new CoreException("该比赛不存在此选手");
        }

        if(!PlayerStateEnum.ENABLE.getCode().equals(player.getState())){
            throw new CoreException("此选手在该比赛中未生效");
        }

    }
    @Override
    public BigDecimal checkScore(int userId, int competitionId){
        LambdaQueryWrapper<CompetitionPlayer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CompetitionPlayer::getUserId, userId)
                .eq(CompetitionPlayer::getCompetitionId, competitionId);
        CompetitionPlayer competitionPlayer = getOne(queryWrapper, false);
        if(competitionPlayer == null){
            throw new CoreException("未查询到该报名信息");
        }
        return competitionPlayer.getScore();
    }
}
